#!/usr/bin/perl

use Getopt::Long qw(:config pass_through);

GetOptions(\%opt,"lines|n=s", "bytes|c=s","verbose","help","quiet|silent|q") 
	|| die("Try zhead --help\n");

if ($ARGV[0] =~ /^-(\d+)/ && ! $opt{lines}) {
	$opt{lines}=$1;
	shift @ARGV;
}

$opt{lines} = 10 if !$opt{lines} && !$opt{bytes};

if ($opt{help}) {
	print "zhead is similar to head... see below.\n\n";
	exec("head --help");
}

if ($opt{lines} =~ s/([a-z]+)$//) {
	$i=lc($1);
	$opt{lines} = $opt{lines} * ( 
		$i eq 'b' ? 512 :
		$i eq 'kb' ? 1000 :
		$i eq 'k' ? 1000 :
		$i eq 'mb' ? 1000*1000 :
		$i eq 'm' ? 1024*1024 :
		$i eq 'gb' ? 1000*1000*1000 :
		$i eq 'g' ? 1024*1024*1024 :
		1					# if your using it for TB ... please don't
	);
}

$ARGV[0] = '-' if (!@ARGV);

$first = 1;
for (@ARGV) {
    open(IN, $_) || die "zhead: cannot open `$_' for reading: $!\n";
    if (/\.gz$/) {
        close IN;
        $_=~ s/'/'"'"'/g;
        open(IN, "gunzip -c '$_' |") || die "$!\n";
    }
	if (@ARGV > 1 && ! $opt{quiet}) {
		print "\n" if !$first;
		print "==> $_ <==\n";
		$first = 0;
	}
	$l = 0;
	if ($opt{lines}) {
		while (<IN>) {
			++$l;
			print;
			last if $l >= $opt{lines};
		}
	} elsif ($opt{bytes}) {
		$r = $opt{bytes};	# bytes remaining
		while(($l=read(IN,$b,$r))>0) {
			$r-=$l;
			print $b;
		}	
	}
	close IN;
}
